class ImagesController < ApplicationController
  # GET /images
  # GET /images.xml
  def index
    @images = Image.all(:order => "created_at DESC", :limit => 20)

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @images }
    end
  end

  # GET /images/1
  # GET /images/1.xml
  def show
    @image = Image.find_last_by_permalink(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @image }
    end
  end

  # DELETE /images/1
  # DELETE /images/1.xml
  def destroy
    @image = Image.find_last_by_permalink(params[:id])
    @image.destroy

    respond_to do |format|
      format.html { redirect_to(images_url) }
      format.xml  { head :ok }
    end
  end

  def image
    @image = Image.find_last_by_permalink(params[:id])
    headers["Content-Type"] = "image/jpeg"
    path = thumb(@image, params[:width], params[:height], params[:fit_width])
    render :text => File.open(path, "rb") { |f|  f.read }, :layout => false
  end

  private
  def thumb(image, width, height, fit_width)
    path = "#{image.path}.thumb.#{width}x#{height}.jpg"
    unless File.exist?(path) then
      img = Magick::Image::read(image.path).first

      if fit_width then
        ratio = img.rows.to_f / img.columns.to_f
        height = (ratio * width.to_i).to_i
      end

      thumb = img.resize_to_fit!(width, height)
      thumb.write path
    end
    path
  end
end
